﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Zwms.Data.BusinessObjects;
using Zwms.Data.CommonObject;
using System.IO;
using NPOI.HSSF.UserModel;


namespace Zwms.Client.InfoWms
{
    public partial class GoodsWnd : UserControl
    {
        #region 成员函数
        private BaseGood _currentQueryRecord;
        private PagerIndex _pagerIndex;
        private BaseGood _selectedRecord;
        public BaseGood SelectedRecord { get { return _selectedRecord; } }
        private CommonUI.WaitForm _waitForm = new CommonUI.WaitForm();
        #endregion

        #region 事件
        public delegate void ButtonClickHandler(object sender, EventArgs e);
        public event ButtonClickHandler BtnConfirmClick;
        public event ButtonClickHandler BtnCancelClick;

        #endregion

        #region 构造函数
        public GoodsWnd()
        {
            InitializeComponent();
            InitBtnImage();
            InitControl();
        }
        #endregion

        #region 公共函数

        public void SetQueryState()
        {
            btnNew.Enabled = false;
            btnEdit.Enabled = false;
            btnDelete.Enabled = false;

            btnConfirm.Visible = true;
            btnCancel.Visible = true;
        }
        #endregion

        #region 私有函数
        private void InitBtnImage()
        {
            this.btnNew.Image = global::Zwms.Client.Properties.Resources.add;
            this.btnEdit.Image = global::Zwms.Client.Properties.Resources.edit;
            this.btnDelete.Image = global::Zwms.Client.Properties.Resources.remove;
            this.btnQuery.Image = global::Zwms.Client.Properties.Resources.query;
            this.btnInput.Image = global::Zwms.Client.Properties.Resources.list;
            this.btnConfirm.Image = global::Zwms.Client.Properties.Resources.ok;
            this.btnCancel.Image = global::Zwms.Client.Properties.Resources.exit;
        }
        private void InitControl()
        {
            ResetDataPager();
            ResetQueryRecord();
            RefreshData();
        }

        private void ResetDataPager()
        {
            dataPager.PageCurrent = 1;
            dataPager.PageSize = CommonDefine.iPageSize;
        }

        private void ResetQueryRecord()
        {
            _currentQueryRecord = new BaseGood();
        }

        private void RefreshData()
        {
            //读入部分数据
            _pagerIndex = new PagerIndex(dataPager.PageCurrent, CommonDefine.iPageSize);
            MyDataBind(_currentQueryRecord, _pagerIndex);
        }

        private void Add()
        {
            GoodsForm window = new GoodsForm(EnumOpenType.New, null);
            if (window.ShowDialog() == DialogResult.OK)
            {
                RefreshData();
            }
        }
        private void Edit()
        {
            if (dgv.CurrentCell == null)
            {
                MessageBox.Show("请选择要编辑的项");
                return;
            }
            int rowIndex = dgv.CurrentCell.RowIndex;

            if (rowIndex < 0)
            {
                return;
            }
            DataGridViewRow row = dgv.Rows[rowIndex];
            BaseGood record = row.DataBoundItem as BaseGood;
            GoodsForm window = new GoodsForm(EnumOpenType.Open, record.Id);
            if (window.ShowDialog() == DialogResult.OK)
            {
                RefreshData();
            }
        }
        private void Delete()
        {
            if (dgv.CurrentCell == null)
            {
                MessageBox.Show("请选择要删除的项");
                return;
            }
            int rowIndex = dgv.CurrentCell.RowIndex;
            if (rowIndex < 0)
            {
                return;
            }

            if (MessageBox.Show("是否确认删除所选择的项？", "确认", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            {
                return;
            }

            DataGridViewRow row = dgv.Rows[rowIndex];
            BaseGood record = row.DataBoundItem as BaseGood;
            try
            {
                //删除操作
                ServiceReferenceZwms.ServiceZwmsClient client = new ServiceReferenceZwms.ServiceZwmsClient();
                client.DeleteGoods(record);

                //删除列表中的该行记录
                InitControl();
            }
            catch (System.Exception exc)
            {
                MessageBox.Show(this, "删除项出错，错误：" + exc.Message, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void MyDataBind(BaseGood queryRecord, PagerIndex pIndex)
        {
            try
            {
                ServiceReferenceZwms.ServiceZwmsClient client = new ServiceReferenceZwms.ServiceZwmsClient();
                IList<BaseGood> queryList = client.QueryGoodsList(queryRecord, ref pIndex);
                dataPager.RecordCount = pIndex.RecordCount;
                LoadBillDetail(queryList);
            }
            catch
            {
            }
        }

        private void LoadBillDetail(IList<BaseGood> recordList)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                this.baseGoodBindingSource.DataSource = null;
                this.baseGoodBindingSource.DataSource = recordList;
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void SelectConfirm()
        {
            if (dgv.CurrentCell == null)
            {
                MessageBox.Show("请首先在列表中选中项");
                return;
            }
            int rowIndex = dgv.CurrentCell.RowIndex;

            if (rowIndex < 0)
            {
                MessageBox.Show("请首先在列表中选中项！");
                return;
            }
            DataGridViewRow row = dgv.Rows[rowIndex];
            _selectedRecord = row.DataBoundItem as BaseGood;
            if (this.Parent is Form)
            {
                Form window = this.Parent as Form;
                window.DialogResult = DialogResult.OK;
                window.Close();
            }
            else
            {
                return;
            }
        }
        #endregion

        #region 控件函数
        private void btnNew_Click(object sender, EventArgs e)
        {
            Add();
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            Edit();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            Delete();
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            ResetDataPager();
            ResetQueryRecord();
            _currentQueryRecord.Id = tbGoodsCode.Text;
            _currentQueryRecord.GoodsName = tbGoodsName.Text;
            _currentQueryRecord.CategoryName = tbsGoodsCategory.GetTextBoxContent();
            _currentQueryRecord.ManufactoryName = tbManufactor.Text;
            RefreshData();
        }

        private void btnInput_Click(object sender, EventArgs e)
        {
            OpenFileDialog oDlg = new OpenFileDialog();
            oDlg.Filter = "*.xls|*.xls";
            if (oDlg.ShowDialog() == DialogResult.OK)
            {
                //打开文件
                FileStream fileTemplate = new FileStream(oDlg.FileName, FileMode.Open, FileAccess.Read);
                HSSFWorkbook hssfworkbook = new HSSFWorkbook(fileTemplate);
                //获取工作簿
                HSSFSheet sheet = hssfworkbook.GetSheetAt(0) as HSSFSheet;
                int iStartRow = 2;
                HSSFRow row = sheet.GetRow(iStartRow) as HSSFRow;

                List<BaseGood> goodsList = new List<BaseGood>();
                while (row != null && row.GetCell(0) != null)
                {
                    BaseGood goodrecord = new BaseGood();
                    Helper.CommonHelper.InitClass<BaseGood>(goodrecord);
                    //货物编码
                    if (row.GetCell(1) != null)
                    {
                        try
                        {
                             goodrecord.Id  = row.GetCell(1).ToString();
                        }
                        catch
                        {
                            continue;
                        }
                    }
                    //货物名称
                    if (row.GetCell(3) != null)
                    {
                        try
                        {
                            goodrecord.GoodsName = row.GetCell(3).ToString();
                        }
                        catch
                        {
                            goodrecord.GoodsName ="";
                        }
                    }

                    //基本单位
                    if (row.GetCell(4) != null)
                    {
                        try
                        {
                            goodrecord.GoodsUnit = row.GetCell(4).ToString();
                        }
                        catch
                        {
                            goodrecord.GoodsUnit = "";
                        }
                    }

                    //物料组描述
                    if (row.GetCell(5) != null)
                    {
                        try
                        {
                            goodrecord.ShortName = row.GetCell(5).ToString();
                        }
                        catch
                        {
                            goodrecord.ShortName = "";
                        }
                    }

                    //单品条形码
                    if (row.GetCell(11) != null)
                    {
                        try
                        {
                            goodrecord.SingleGoodsCode = row.GetCell(11).ToString();
                        }
                        catch
                        {
                            goodrecord.SingleGoodsCode = "";
                        }
                    }

                    //零售价
                    if (row.GetCell(12) != null)
                    {
                        try
                        {
                            goodrecord.RetailPrice = Convert.ToDecimal(row.GetCell(12).ToString());
                        }
                        catch
                        {
                            goodrecord.RetailPrice = 0;
                        }
                    }

                    //规格
                    if (row.GetCell(13) != null)
                    {
                        try
                        {
                            goodrecord.Specs = int.Parse(row.GetCell(13).ToString());
                        }
                        catch
                        {
                            goodrecord.Specs = 0;
                        }
                    }

                    //单个体积
                    if (row.GetCell(14) != null)
                    {
                        try
                        {
                            goodrecord.PieceVolume = Convert.ToDecimal(row.GetCell(14).ToString());
                        }
                        catch
                        {
                            goodrecord.PieceVolume = 0;
                        }
                    }

                    //单个重量
                    if (row.GetCell(15) != null)
                    {
                        try
                        {
                            goodrecord.PieceWeight = Convert.ToDecimal(row.GetCell(15).ToString());
                        }
                        catch
                        {
                            goodrecord.PieceWeight = 0;
                        }
                    }

                    //单个净含量
                    if (row.GetCell(16) != null)
                    {
                        try
                        {
                            goodrecord.PieceNetContent = Convert.ToDecimal(row.GetCell(16).ToString());
                        }
                        catch
                        {
                            goodrecord.PieceNetContent = 0;
                        }
                    }

                    //长
                    if (row.GetCell(17) != null)
                    {
                        try
                        {
                            goodrecord.GoodsLength = Convert.ToDecimal(row.GetCell(17).ToString());
                        }
                        catch
                        {
                            goodrecord.GoodsLength = 0;
                        }
                    }

                    //宽
                    if (row.GetCell(18) != null)
                    {
                        try
                        {
                            goodrecord.GoodsWidth = Convert.ToDecimal(row.GetCell(18).ToString());
                        }
                        catch
                        {
                            goodrecord.GoodsWidth = 0;
                        }
                    }

                    //高
                    if (row.GetCell(19) != null)
                    {
                        try
                        {
                            goodrecord.GoodsHeight = Convert.ToDecimal(row.GetCell(19).ToString());
                        }
                        catch
                        {
                            goodrecord.GoodsHeight = 0;
                        }
                    }

                    //箱体积
                    if (row.GetCell(20) != null)
                    {
                        try
                        {
                            goodrecord.GoodsVolume = Convert.ToDecimal(row.GetCell(20).ToString());
                        }
                        catch
                        {
                            goodrecord.GoodsVolume = 0;
                        }
                    }

                    //箱重量
                    if (row.GetCell(21) != null)
                    {
                        try
                        {
                            goodrecord.GoodsWeight = Convert.ToDecimal(row.GetCell(21).ToString());
                        }
                        catch
                        {
                            goodrecord.GoodsWeight = 0;
                        }
                    }
                    goodsList.Add(goodrecord);

                    iStartRow++;
                    row = sheet.GetRow(iStartRow) as HSSFRow;
                }

                if (MessageBox.Show(string.Format("读取到{0}条商品信息，是否确认添加到数据库中？",goodsList.Count), "注意", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                {
                    return;
                }
                //
                ServiceReferenceZwms.ServiceZwmsClient client = new ServiceReferenceZwms.ServiceZwmsClient();
                if (client.AddGoodsList(goodsList.ToArray()))
                {
                    MessageBox.Show("导入数据成功");
                }
                else
                {
                    MessageBox.Show("导入数据失败");
                }
            }
        }

        private void dataPager_BtnClick(object sender, EventArgs e)
        {
            _pagerIndex.CurrentPageIndex = dataPager.PageCurrent;
            MyDataBind(_currentQueryRecord, _pagerIndex);
        }

        private void dgv_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            SelectConfirm();
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            SelectConfirm();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (this.Parent is Form)
            {
                Form window = this.Parent as Form;
                window.DialogResult = DialogResult.Cancel;
                window.Close();
            }
            else
            {
                return;
            }
        }

        private void tbsGoodsCategory_SelectButtonClick(object sender, EventArgs e)
        {
            InfoWms.GoodsCategoryWnd uc = new InfoWms.GoodsCategoryWnd();
            CommonUI.ContainerForm window = new CommonUI.ContainerForm(uc, "货物分类信息");
            uc.SetQueryState();
            if (window.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                tbsGoodsCategory.SetTextBoxContent(uc.SelectedRecord.CategoryName);
                tbsGoodsCategory.Tag = uc.SelectedRecord.Id;

            }
        }


        #endregion

       
    }
}
